#!/sbin/openrc-run
# Copyright 1999-2013 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

depend() {
	# need net
	use dns logger net
}

parse_opts() {
	local filter_opt filter_flag=
	for filter_opt in ${SID_FILTER_OPTS}; do
		case "${filter_flag}" in
			-u)	filter_user=${filter_opt}
				;;
			-P)	filter_pid=${filter_opt}
				;;
		esac
		[ -n "${filter_user}" -a -n "${filter_pid}" ] && break
		filter_flag=${filter_opt}
	done

	if [ -z "${filter_user}" ]; then 
		filter_user=milter
		SID_FILTER_OPTS="${SID_FILTER_OPTS} -u ${filter_user}"
	fi
	if [ -z "${filter_pid}" ]; then 
		filter_pid="/var/run/sid-filter.pid"
		SID_FILTER_OPTS="${SID_FILTER_OPTS} -P ${filter_pid}"
	fi
}

clean_socket() {
	local socket_file= svc_pid=

	socket_file="$(echo ${SID_FILTER_OPTS} | sed -e 's/.*local:\(.*\) .*/\1/' | awk '{print $1}')"
	svc_pid="$(ps -C sid-filter -o pid=)"
	if [[ -z "${svc_pid}" ]]  && [[ ! -z "${socket_file}" ]] && [[ -S "${socket_file}" ]]; then
		ewarn "Strange, the socket file already exist in \"${socket_file}\""
		ewarn "it will be removed now and re-created by the sid-filter server"
		ewarn "BUT please make your checks."
		rm -f "${socket_file}"
	fi
}

check_socketdir() {
	local socket_dir
	case "${SOCKETSPEC}" in
		local:*) socket_dir="$(echo ${SOCKETSPEC} | sed -e 's~^local:\(.*\)/.*$~\1~')"
			if [[ ! -d ${socket_dir} ]]; then
				checkpath -q -d -o ${filter_user}:${filter_user} -m 0755 ${socket_dir} || return 1
			fi ;;
		inet:*) ;;
		*)      eerror "Unknown socket spec.  Please check your /etc/conf.d/sid-milter file."
			return 1 ;;
	esac
}


start() {
	local filter_user= filter_pid=

	clean_socket
	parse_opts
	check_socketdir || return 1
	if ! (touch ${filter_pid} && chown ${filter_user} ${filter_pid}) ; then
		eerror "Failed to create pidfile"
		return 1
	fi

	ebegin "Starting Sender-ID Filter"
	start-stop-daemon --start --exec /usr/bin/sid-filter -- ${SID_FILTER_OPTS}
	eend $?
}

stop() {
	local filter_user= filter_pid=

	parse_opts

	ebegin "Stopping Sender-ID Filter"
	start-stop-daemon --stop --quiet --name sid-filter --pidfile ${filter_pid}
	eend $?

	if [ $? = 0 -a -f "${filter_pid}" ]; then
		rm ${filter_pid}
	fi
}
